//
//  OAuthViewController.swift
//  JIMWeiBo
//
//  Created by 陈恒均 on 2018/2/10.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavBar()
        
        loadPage()
        
        webView.delegate = self
    }

    
}
// MARK:- 设置UI界面
extension OAuthViewController
{
    func setupNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OAuthViewController.closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(OAuthViewController.fillItemClick))
        
        title = "登录界面"
    }
    
    func loadPage(){
        let urlstring = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        guard let url = NSURL(string: urlstring) else{
            return
        }
        let request = NSURLRequest(url: url as URL)
        
        webView.loadRequest(request as URLRequest)
        
        
        
    }
    
    
}
// MARK:- 事件监听
extension OAuthViewController
{
    @objc private func closeItemClick() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func fillItemClick() {
        let jsCode = "document.getElementById('userId').value='13850745359';document.getElementById('passwd').value='20160510cyq';"
        
        webView.stringByEvaluatingJavaScript(from: jsCode)
  
        
    }
}

extension OAuthViewController:UIWebViewDelegate
{
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else {
            return true
        }
        let urlString = url.absoluteString
        
        guard urlString.contains("code=") else
        {
            return true
        }
        
        let code = urlString.components(separatedBy:"code=").last!
        
        
        loadAccessToken(code: code)
        
        return false
    }
}

extension OAuthViewController
{
    func loadAccessToken(code:String){
        
        NetworkTools.shareInstance.loadAccessToken(code: code) { (result, error) in
            
            if error != nil {
//                print(error)
                return
            }
            
            // 2.拿到结果
            guard let accountDict = result else {
                print("没有获取授权后的数据")
                return
            }
            
            // 3.将字典转成模型对象
            
            let account = UserAccount(dict: accountDict)
            
//            print()
            self.loadUserInfo(accout: account)
        
        }
    }
    //请求用户信息
    func loadUserInfo(accout:UserAccount) {
        guard let accessToken = accout.access_token else {
            return
        }

        guard let uid = accout.uid else{
            return
        }

        NetworkTools.shareInstance.loadUserInfo(access_token: accessToken, uid: uid) { (result, error) in
            if error != nil{
                return
            }

            guard let userInfoDict = result else{
                return
            }

            accout.screen_name = userInfoDict["screen_name"] as? String
            accout.avatar_large = userInfoDict["avatar_large"] as? String

           
            
            NSKeyedArchiver.archiveRootObject(accout, toFile: UserAccountViewModel.shareInstance.accountPath)
            
            UserAccountViewModel.shareInstance.account = accout
            
            
            self.dismiss(animated: false, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
            })
        }


    }
}






